package com.tumblshow;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;

public class Parser extends DefaultHandler {
	/*	MEMBER VARIABLES	*/
	private Context ctx;
	private DbAdapter dbAdapter;
	private boolean item;
	private boolean link;

	private String buffer = "";
	private long id;
	private String from;
	private String title;

	/*	CONSTRUCTORS	*/
	public Parser(Context ctx, String link){
		super();
		this.ctx = ctx;
		this.from = link;
	}
	
	/*	INHERITED METHODS	*/
	@Override
	public void startDocument() throws SAXException {
		dbAdapter = new DbAdapter(ctx);
		dbAdapter.open();
	}
	
	@Override
	public void endDocument() throws SAXException {
		dbAdapter.close();
	}

	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
		buffer = "";
		
		if(localName.equals("item")){
			item = true;
		} else if(localName.equals("link")){
			link = true;
		} else if(localName.equals("img") && link && item){
			dbAdapter.imgCreate(id, atts.getValue("src"));
		}
	}
	
	@Override
	public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
		if(localName.equals("item")){
			item = false;
		} else if(localName.equals("link")){
			link = false;
		} else if(localName.equals("title") && !item){
			title = buffer;
			id = dbAdapter.tumblrCreate(title, from);
		}
	}

	@Override
	public void characters(char ch[], int start, int length){
		buffer = buffer + new String(ch, start, length);
	}
}
